﻿''' <summary>
''' This implementation of the IRolesRepository uses web.config to store users (yeah, this is the "real" one)
''' so it can only be run in the context of a web application. 
''' For testing purposes, consider using a mock/stub
''' implementation of IRoleRepository (such as StubRolesRepository).
''' </summary>
Public Class WebConfigRolesRepository
  Implements Interfaces.IRolesRepository

  Public Sub New()
    Dim section As ConfigurationSection = Core.ConfigurationSection.GetConfig

    Call _lRoles.AddRange(From r In section.Roles.Cast(Of ConfigurationElement)() Select New Role(r.Name, r.Users))
  End Sub

  Private _lRoles As New List(Of Role)
  Public ReadOnly Property Roles() As System.Collections.Generic.List(Of Role) Implements Interfaces.IRolesRepository.Roles
    Get
      Return _lRoles
    End Get
  End Property

  Public Sub Save() Implements Interfaces.IRolesRepository.Save
    Dim config = Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~")
    Dim section As ConfigurationSection = CType(config.GetSection("WebConfigRoleProvider"), ConfigurationSection)

    Call section.Roles.Clear()

    For Each role In _lRoles
      Call section.Roles.Add(New ConfigurationElement With {.Name = role.Name, .Users = Join((From u In role.Users Where u <> "" Order By u).Distinct().ToArray, ", ")})
    Next

    Call config.Save()
  End Sub
End Class
